package org.jnarcissus;

import java.lang.reflect.Method;
import java.util.ArrayList;

import net.sf.cglib.proxy.MethodProxy;

import org.objectweb.asm.Type;

public class MonitoredInstanceData {

	private ArrayList<MonitoredInstanceMethodCall> methods = null;
	public static final Type TYPE = Type.getType(MonitoredInstanceData.class);

	/**
	 * Serialization id.
	 */
	private static final long serialVersionUID = 1L;

	public MonitoredInstanceMethodCall getMethod(IMonitoredInstance source, Method method, Object[] arguments, MethodProxy methodProxy) {

		// Creates a new temporary method just to check if the HashSet contains one that matches 
		MonitoredInstanceMethodCall tempMethod = new MonitoredInstanceMethodCall(source, method, arguments, methodProxy);

		if (methods == null)
			methods = new ArrayList<MonitoredInstanceMethodCall>();

		MonitoredInstanceMethodCall realMethod = null;
		
		int idxExisting = methods.indexOf(tempMethod);
		
		if (idxExisting == -1) {

			methods.add(tempMethod);
			realMethod = tempMethod;

		} else {

			realMethod = methods.get(idxExisting);
		}

		return realMethod;
	}

	public int getMonitoredMethodsCount() {

		return (methods != null) ? methods.size() : 0;
	}

	/**
	 * Executes all previous asserts made.
	 */
	public void andPreviousAsserts() {

		if (methods != null) {

			for (MonitoredInstanceMethodCall method : methods) {

				method.executeAsserts();
			}
		}
	}
}
